package ling.archives.common;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.StringUtils;
import lombok.var;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class ValidUtil {
    static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    public static String[] valid(Object obj) {
        var list = new ArrayList<String>();
        for (ConstraintViolation<Object> violation : validator.validate(obj)) {
            list.add(violation.getMessage() + "[" + violation.getPropertyPath().toString() + "]");
        }
        return list.toArray(new String[0]);
    }

    public static String validToStr(Object obj) {
        var violations = validator.validate(obj);
        if (violations.isEmpty()) {
            return "";
        }

        StringBuilder msg = new StringBuilder();
        for (var violation : violations) {
            msg.append("字段[")
               .append(violation.getPropertyPath())
               .append("]验证失败: ")
               .append(violation.getMessage())
               .append(" (当前值: '")
               .append(violation.getInvalidValue())
               .append("', 约束: '")
               .append(violation.getConstraintDescriptor().getAnnotation())
               .append("'); \n");
        }
        return msg.toString();
    }

    public static R validToR(Object obj) {
        var err = validToStr(obj);
        if (StringUtils.isNotBlank(err))
            return R.fail(err);
        return R.ok();
    }

    public static R validList(Collection<?> objs) {
        for (Object obj : objs) {
            var r = validToR(obj);
            if (!R.isSuccess(r))
                return r;
        }
        return R.ok();
    }
}